<template>
  <div class="add">
    <el-card class="add-container">
      <el-form
        :model="goodForm"
        :rules="rules"
        ref="goodRef"
        label-width="100px"
        class="goodForm"
      >
        <el-form-item required label="商品分类">
          <el-cascader
            :placeholder="defaultCate"
            style="width: 300px"
            :props="category"
            @change="handleChangeCate"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="goodForm.goodsName"></el-input>
        </el-form-item>
        <el-form-item label="商品简介" prop="goodsIntro">
          <el-input v-model="goodForm.goodsIntro" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="originalPrice">
          <el-input v-model="goodForm.originalPrice"></el-input>
        </el-form-item>
        <el-form-item label="商品售卖价" prop="sellingPrice">
          <el-input v-model="goodForm.sellingPrice"></el-input>
        </el-form-item>
        <el-form-item label="商品库存" prop="stockNum">
          <el-input v-model="goodForm.stockNum"></el-input>
        </el-form-item>
        <el-form-item label="商品标签" prop="tag">
          <el-input v-model="goodForm.tag"></el-input>
        </el-form-item>
        <el-form-item prop="goodsSellStatus" label="商品状态">
          <el-radio-group v-model="goodForm.goodsSellStatus">
            <el-radio label="0">上架</el-radio>
            <el-radio label="1">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品主图" prop="goodsCoverImg">
          <el-upload
            class="avatar-uploader"
            :action="uploadImgServer"
            :headers="{
              token: token,
            }"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              style="width: 100px; height: 100px; border: 1px solid #e9e9e9"
              v-if="goodForm.goodsCoverImg"
              :src="goodForm.goodsCoverImg"
              class="avatar"
            />
            <el-icon v-else class="el-icon-plus avatar-uploader-icon"></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="详情内容">
          <div ref="editor"></div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAdd()">{{
            id!=0 ? "立即修改" : "立即创建"
          }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { reactive, toRefs, ref, getCurrentInstance, onMounted, onBeforeUnmount } from "vue";
import { useRoute, useRouter } from "vue-router";
import { uploadImgServer, uploadImgsServer, localGet } from "@/utils";
import {ElMessage} from "element-plus";
import axios from "@/utils/axios";
import WangEditor from "wangeditor";
export default {
  name: "AddGood",
  setup() {
    // const { proxy } = getCurrentInstance();
    const goodRef = ref(null); //表单ref
    const editor = ref(null); //富文本编辑器ref
    const router = useRouter();
    const route = useRoute();
    const { id } = route.query;
    const state = reactive({
      uploadImgServer,
      token: localGet("token") || "",
      defaultCate: "",
      goodForm: {
        goodsName: "",
        goodsIntro: "",
        originalPrice: "",
        sellingPrice: "",
        stockNum: "",
        goodsCoverImg: "",
        tag: "",
      },
      rules: {
        goodsName: [
          { required: "true", message: "请填写商品名称", trigger: ["change"] },
        ],
        originalPrice: [
          { required: "true", message: "请填写商品价格", trigger: ["change"] },
        ],
        sellingPrice: [
          { required: "true", message: "请填写商品售价", trigger: ["change"] },
        ],
        stockNum: [
          { required: "true", message: "请填写商品库存", trigger: ["change"] },
        ],
      },
      categoryId: "",
      // 分类懒加载
      category: {
        lazy: true,
        lazyLoad(node, resolve) {
          const { level = 0, value } = node;
          axios
            .get("/categories", {
              params: {
                pageNumber: 1,
                pageSize: 1000,
                categoryLevel: level + 1,
                parentId: value || 0,
              },
            })
            .then((res) => {
              const list = res.list;
              const nodes = list.map((item) => ({
                value: item.categoryId,
                label: item.categoryName,
                leaf: level > 1,
              }));
              resolve(nodes);
            });
        },
      },
    });
    let instance; //wangEditor 的实例
    onMounted(() => {
      instance = new WangEditor(editor.value); //初始化wangEditor 实例
      instance.config.showLinkImg = false; //隐藏网络图片
      instance.config.showLinkImgAlt = false;
      instance.config.showLinkImgHref = false; //隐藏插入网络图片功能可以分别设置添加alt属性和跳转链接
      instance.config.uploadImgMaxSize = 2 * 1024 * 1024; //最大上传大小2M
      instance.config.uploadFileName = "file"; //上传时，key值自定义
      instance.config.uploadImgHeaders = {
        token: state.token, //添加token，否则没有权限调用上传接口
      };
      //图片返回格式不同，需要自定义返回格式
      instance.config.uploadImgHooks = {
        //图片上传并返回了结果，把自己想要的图片插入到编辑器中
        // 例如服务器端返回的不是 { errno: 0, data: [...] } 这种格式，可使用 customInsert
        customInsert: function (insertImgFn, result) {
          console.log("result", result);
          console.log('result.data.length',result.data.length);
          // result 即服务端返回的接口
          //insertImgFn 可把图片插入到编辑器，传入图片src，执行函数即可
          if (result.data && result.data.length) {
            // insertImgFn(result.data)
            result.data.forEach((item) => insertImgFn(item));
          }
        },
      };
      // 配置上传图片接口配置
      instance.config.uploadImgServer = uploadImgsServer;
      Object.assign(instance.config, {
        onchange() {
          console.log("change");
        },
      });
      instance.create();
      if(id){
        //获取商品详情
        axios.get(`/goods/${id}`).then(res=>{
          const {goods,firstCategory,secondCategory,thirdCategory}=res
          console.log(res);
          state.goodForm={
            goodsName:goods.goodsName,
            goodsIntro:goods.goodsIntro,
            originalPrice:goods.originalPrice,
            sellingPrice:goods.sellingPrice,
            stockNum:goods.stockNum,
            goodsSellStatus:String(goods.goodsSellStatus),
            goodsCoverImg:goods.goodsCoverImg,
            tag:goods.tag
          }
          state.categoryId=goods.goodsCategoryId
          state.defaultCate=`${firstCategory.categoryName}/${secondCategory.categoryName}/${thirdCategory.categoryName}`
          if(instance){
            instance.txt.html(goods.goodsDetailContent)
          }
        })
      }
    });
    const beforeAvatarUpload = (file) => {
      console.log("file: ", file);
      const sufix = file.name.split(".")[1] || "";
      if (!["jpg", "png", "jpeg"].includes(sufix)) {
        ElMessage.error("请上传jpg,png,jpeg格式的图片");
        return false;
      }
    };
    const handleAvatarSuccess = (val) => {
      state.goodForm.goodsCoverImg = val.data;
    };
    const handleChangeCate = (val) => {
      console.log(val);
       state.categoryId = val[2] || 0
    };
    const submitAdd = () => {
      goodRef.value.validate((valid)=>{
        if(valid){
          //默认新增用post方法
          let httpOption=axios.post
          let params={
            goodsCategoryId:state.categoryId,
            goodsCoverImg:state.goodForm.goodsCoverImg,
            goodsDetailContent:instance.txt.html(),   //????
            goodsIntro:state.goodForm.goodsIntro,
            goodsName:state.goodForm.goodsName,
            goodsSellStatus:state.goodForm.goodsSellStatus,
            originalPrice:state.goodForm.originalPrice,
            sellingPrice:state.goodForm.sellingPrice,
            stockNum:state.goodForm.stockNum,
            tag:state.goodForm.tag
          }
          console.log('params: ', params);
          if(id){
            //编辑
            httpOption=axios.put
            params.goodsId=id
          }
          httpOption('/goods',params).then(()=>{
            ElMessage.success(id?'修改成功':'添加成功')
            router.push({path:'/good'})
          })
        }
      })
    };
    onBeforeUnmount(() => {
      instance.destroy()
      instance = null
    })
    return {
      ...toRefs(state),
      beforeAvatarUpload,
      handleAvatarSuccess,
      handleChangeCate,
      submitAdd,
      editor,
      goodRef,
    };
  },
};
</script>

<style scoped>
/* .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  
} */
.avatar-uploader .avatar-uploader-icon:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
/*  */
/* .avatar-uploader {
    width: 100px;
    height: 100px;
    color: #ddd;
    font-size: 30px;
  }
  .avatar-uploader-icon {
    display: block;
    width: 100%;
    height: 100%;
    border: 1px solid #e9e9e9;
    padding: 32px 17px;
  } */
</style>